<template>
  <el-dialog
    v-model="visible"
    title="扫描二维码/条形码"
    width="90%"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    @close="handleClose"
    class="qr-scanner-dialog"
  >
    <div class="scanner-container">
      <!-- 扫描预览区域 -->
      <div class="scanner-preview">
        <div id="qr-reader" ref="qrReaderRef"></div>
        <div v-if="!isScanning && !error" class="scanner-placeholder">
          <el-icon size="48"><Camera /></el-icon>
          <p>点击开始扫描按钮启动摄像头</p>
        </div>
        <div v-if="error" class="scanner-error">
          <el-icon size="48"><Warning /></el-icon>
          <p>{{ error }}</p>
        </div>
      </div>

      <!-- 扫描指示框 -->
      <div v-if="isScanning" class="scan-frame">
        <div class="scan-line"></div>
      </div>

      <!-- 控制按钮 -->
      <div class="scanner-controls">
        <el-button
          v-if="!isScanning"
          type="primary"
          size="large"
          @click="startScanning"
          :loading="starting"
        >
          <el-icon><Camera /></el-icon>
          开始扫描
        </el-button>
        
        <el-button
          v-if="isScanning"
          type="danger"
          size="large"
          @click="stopScanning"
        >
          <el-icon><Close /></el-icon>
          停止扫描
        </el-button>

        <el-button
          size="large"
          @click="handleClose"
        >
          取消
        </el-button>
      </div>

      <!-- 使用说明 -->
      <div class="scanner-tips">
        <el-alert
          title="使用提示"
          type="info"
          :closable="false"
          show-icon
        >
          <ul>
            <li>请将二维码或条形码对准扫描框</li>
            <li>保持适当距离，确保代码清晰可见</li>
            <li>支持订单号二维码和条形码扫描</li>
            <li>扫描成功后会自动填入订单号</li>
          </ul>
        </el-alert>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onUnmounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Camera, Warning, Close } from '@element-plus/icons-vue'
import { Html5QrcodeScanner, Html5QrcodeScanType } from 'html5-qrcode'

// Props
interface Props {
  modelValue: boolean
}

// Emits
interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'scan-success', result: string): void
  (e: 'scan-error', error: string): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const visible = ref(false)
const isScanning = ref(false)
const starting = ref(false)
const error = ref('')
const qrReaderRef = ref<HTMLElement>()

// 扫描器实例
let html5QrcodeScanner: Html5QrcodeScanner | null = null

// 监听 modelValue 变化
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    error.value = ''
  } else {
    stopScanning()
  }
})

// 监听 visible 变化
watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

// 开始扫描
const startScanning = async () => {
  try {
    starting.value = true
    error.value = ''

    // 检查浏览器支持
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      throw new Error('您的浏览器不支持摄像头功能')
    }

    await nextTick()

    // 创建扫描器
    html5QrcodeScanner = new Html5QrcodeScanner(
      "qr-reader",
      {
        fps: 10,
        qrbox: { width: 250, height: 250 },
        supportedScanTypes: [Html5QrcodeScanType.SCAN_TYPE_CAMERA],
        rememberLastUsedCamera: true,
        showTorchButtonIfSupported: true,
        showZoomSliderIfSupported: true,
        defaultZoomValueIfSupported: 2,
      },
      false
    )

    // 扫描成功回调
    const onScanSuccess = (decodedText: string) => {
      console.log('🎯 扫描成功:', decodedText)
      
      // 处理扫描结果
      const orderNumber = extractOrderNumber(decodedText)
      
      if (orderNumber) {
        ElMessage.success(`扫描成功：${orderNumber}`)
        emit('scan-success', orderNumber)
        handleClose()
      } else {
        ElMessage.warning('未识别到有效的订单号，请重新扫描')
      }
    }

    // 扫描失败回调
    const onScanFailure = (error: string) => {
      // 这里不显示错误，因为扫描失败很常见
      console.log('扫描中...', error)
    }

    // 启动扫描器
    html5QrcodeScanner.render(onScanSuccess, onScanFailure)
    
    isScanning.value = true
    starting.value = false

  } catch (err: any) {
    console.error('启动扫描失败:', err)
    error.value = err.message || '启动摄像头失败，请检查权限设置'
    starting.value = false
    emit('scan-error', error.value)
  }
}

// 停止扫描
const stopScanning = () => {
  if (html5QrcodeScanner) {
    try {
      html5QrcodeScanner.clear()
    } catch (err) {
      console.warn('清理扫描器失败:', err)
    }
    html5QrcodeScanner = null
  }
  isScanning.value = false
  starting.value = false
}

// 提取订单号
const extractOrderNumber = (scannedText: string): string => {
  // 去除空格和换行
  const cleanText = scannedText.trim()
  
  // 如果直接是订单号格式，直接返回
  if (/^[A-Z0-9-]+$/i.test(cleanText)) {
    return cleanText
  }
  
  // 尝试从URL中提取订单号
  try {
    const url = new URL(cleanText)
    const orderParam = url.searchParams.get('order') || url.searchParams.get('orderNumber')
    if (orderParam) {
      return orderParam
    }
  } catch {
    // 不是URL，继续其他处理
  }

  // 尝试从JSON中提取订单号
  try {
    const jsonData = JSON.parse(cleanText)
    if (jsonData.orderNumber || jsonData.order_number || jsonData.order) {
      return jsonData.orderNumber || jsonData.order_number || jsonData.order
    }
  } catch {
    // 不是JSON，继续其他处理
  }

  // 使用正则表达式匹配可能的订单号模式
  const orderPatterns = [
    /订单号[：:]\s*([A-Z0-9-]+)/i,
    /order[：:\s]*([A-Z0-9-]+)/i,
    /SCDD\d+/i,
    /[A-Z]{2,4}\d{6,}/i
  ]
  
  for (const pattern of orderPatterns) {
    const match = cleanText.match(pattern)
    if (match) {
      return match[1] || match[0]
    }
  }
  
  // 如果都没匹配到，返回原始文本（让用户决定是否有用）
  return cleanText
}

// 关闭对话框
const handleClose = () => {
  stopScanning()
  visible.value = false
}

// 组件卸载时清理
onUnmounted(() => {
  stopScanning()
})
</script>

<style scoped>
.qr-scanner-dialog {
  --el-dialog-margin-top: 5vh;
}

.scanner-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.scanner-preview {
  position: relative;
  width: 100%;
  max-width: 400px;
  min-height: 300px;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
}

.scanner-placeholder,
.scanner-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  color: #909399;
  text-align: center;
}

.scanner-error {
  color: #f56c6c;
}

#qr-reader {
  width: 100%;
  border-radius: 8px;
}

.scan-frame {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 250px;
  height: 250px;
  border: 2px solid #409eff;
  border-radius: 8px;
  pointer-events: none;
}

.scan-line {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, transparent, #409eff, transparent);
  animation: scan-line 2s linear infinite;
}

@keyframes scan-line {
  0% {
    top: 0;
  }
  100% {
    top: 100%;
  }
}

.scanner-controls {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  justify-content: center;
}

.scanner-tips {
  width: 100%;
  max-width: 400px;
}

.scanner-tips ul {
  margin: 0;
  padding-left: 20px;
}

.scanner-tips li {
  margin: 4px 0;
  font-size: 14px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .qr-scanner-dialog {
    --el-dialog-margin-top: 2vh;
  }
  
  .scanner-preview {
    min-height: 250px;
  }
  
  .scan-frame {
    width: 200px;
    height: 200px;
  }
  
  .scanner-controls {
    flex-direction: column;
    width: 100%;
  }
  
  .scanner-controls .el-button {
    width: 100%;
  }
}
</style>
